package com.wise.service.cms.content.industryinformation;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.wise.entities.content.ArticleStatus;
import com.wise.entities.content.IndustryInformation;
import com.wise.framework.basic.DateTimeUtil;
import com.wise.framework.consts.Consts;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.framework.daomodel.DaoSave;
import com.wise.framework.exception.LogicException;
import com.wise.framework.session.CurrentUserId;
import com.wise.framework.session.CurrentUserInfo;
import com.wise.framework.session.GetAcceptLanguage;
import com.wise.summer.v1.cms.content.industryinformation.AddIndustryInformation;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import static com.wise.model.content.ContentErrMsgs.Err_001600250018;
import static com.wise.model.content.ContentErrMsgs.Err_001600250019;

@Service
@SummerService
public class AddIndustryInformationService implements SummerServiceBean<AddIndustryInformation> {
    @Override
    public void sum(AddIndustryInformation model) {
        String lang = GetAcceptLanguage.s(true);
        // 别名不可重复
        model.setAlias(IndustryInformationTools.toNullAlias(model.getAlias()));
        if (IndustryInformationTools.checkAlias(model.getAlias())) {
            throw new LogicException(this.getClass(), Err_001600250019);
        }

        //新闻标题不可重复
        checkIfDuplicateTitle(model.getTitle(), null);
        IndustryInformation article = new IndustryInformation();
        BeanUtil.copyProperties(model, article);

        if (model.getDraftState() == null) {
            model.setDraftState(false);
        }
        if (StringUtils.isEmpty(model.getState())) {
            //保存为未发布状态
            article.setState(ArticleStatus.NOTPUBLISH.value());
        } else {
            article.setState(model.getState());
        }
        article.setLang(lang);
        article.setPageTitle(model.getPageTitle());
        article.setPublishTime(getPublishTimeByState(model.getState(), model.getPublishTime()));
        Map<String, Object> currentUserInfo = CurrentUserInfo.s(true);
        article.setCreatedBy(CurrentUserId.s(true));
        article.setCreationDate(DateTimeUtil.timestampNow());
        article.setAuthor(Convert.toStr(currentUserInfo.get(Consts.USER_PROPERTY_FULL_NAME)));

        // 草稿
        if (model.getDraftState()) {
            String draftJson = JSON.toJSONString(article);
            IndustryInformation must = new IndustryInformation();
            must.setColumnId(model.getColumnId());
            must.setTitle(model.getTitle());
            must.setUrl(model.getUrl());
            must.setIntro(model.getIntro());
            must.setDraft(draftJson);
            must.setLang(lang);
            DaoSave.s(must);
            model.setSummerResult(must);
        } else {
            DaoSave.s(article);
            model.setSummerResult(article);
        }
    }

    /**
     * 检查标题是否重复
     *
     * @param title
     */
    static protected void checkIfDuplicateTitle(String title, String id) {

        SqlSelect queryForArticle = SqlSelect.selec(IndustryInformation._title + "," + IndustryInformation._id)
                .fromClassName(IndustryInformation.class)
                .eqLang(IndustryInformation._lang)
                .eq(IndustryInformation._title, title);
        List<IndustryInformation> articleList = DaoList.s(IndustryInformation.class, queryForArticle);
        if (!articleList.isEmpty() && !articleList.get(0).getId().equals(id)) {
            throw new LogicException(new Throwable().getStackTrace()[1].getClass(), Err_001600250018);
        }

    }

    /**
     * 设置发布时间
     *
     * @param state
     */
    static Timestamp getPublishTimeByState(Integer state, String publishTime) {
        if (ArticleStatus.PUBLISH.isValue(state)) {
            //发布时间默认值 -> 当前时间
            if (publishTime != null) {
                return new Timestamp(Long.parseLong(publishTime));
            }
        }
        return null;
    }
}
